package queryTree.graphic;
/**
 * graphic interfact
 * @author Van
 */
import javax.swing.SwingUtilities;

import java.awt.Component;

import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Dimension;
import javax.swing.JTextArea;
import java.awt.Rectangle;


import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTree;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;

import optimization.Field;
import optimization.SQLParsingException;
import queryTree.BooleanExpr;
import queryTree.JoinNode;
import queryTree.Main;
import queryTree.TableNode;
import queryTree.TreeNode;
import queryTree.AbstractNode;
import costEstimation.*;



import java.awt.Font;
import java.util.ArrayList;

public class QueryInterface extends JFrame {

	private static final long serialVersionUID = 1L;
	private String query;
	public void setQuery(String query) {
		this.query = query;
	}

	private JPanel jContentPane = null;	

	private JTextArea jTAQuery = null;

	private JLabel jLabel = null;

	private JButton jBtnMakeTree = null;

	private JTree jTreeQuery = null;

	private JScrollPane jSPTreeView = null;

	private JTable jTableQueryResult = null;

	private JScrollPane jSPTAQuery = null;
	private JTextArea jTAError = null;
	private JScrollPane jSPError = null;
	private JLabel jLabel1 = null;
	
	
	/**
	 * This method initializes jContentPane1	
	 * 	
	 * @return javax.swing.JPanel	
	 */


	/**
	 * This method initializes jTAQuery	
	 * 	
	 * @return javax.swing.JTextArea	
	 */
	public JTextArea getJTAQuery() {
		if (jTAQuery == null) {
			jTAQuery = new JTextArea();
		}
		return jTAQuery;
	}

	/**
	 * This method initializes jBtnMakeTree	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJBtnMakeTree() {
		if (jBtnMakeTree == null) {
			jBtnMakeTree = new JButton();
			jBtnMakeTree.setBounds(new Rectangle(15, 92, 152, 16));
			jBtnMakeTree.setText("Query Expression");
			jBtnMakeTree.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					// TODO Auto-generated Event stub actionPerformed()
					jTAError.setText("");
					//tao cay
					query=jTAQuery.getText();
					try {
						TreeNode t=Main.getTreeFromSQL(query);
/*						Optimizer opt = new Optimizer();
						t = (TreeNode)opt.optimization((AbstractNode)t);
*/						DefaultMutableTreeNode d=createNodes(t);
						jTreeQuery=new JTree(d);
						jTreeQuery.setCellRenderer(new MyTreeCellRenderer());
						jSPTreeView.setViewportView(jTreeQuery);
					
					} catch (SQLParsingException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
						jTreeQuery.setVisible(false);
						jTAError.setText(e1.getMessage().toString());
					}					
				}
			});
		}
		return jBtnMakeTree;
	}
	public DefaultMutableTreeNode createNodes(TreeNode t)
	{
		DefaultMutableTreeNode result=null;
		if(t instanceof JoinNode)
		{
			JoinNode o=(JoinNode)t;	
			//create projection node
			ProjectionNode pNode = null;
			ArrayList<Field> projectionL = o.getAttrsProjection();
			DefaultMutableTreeNode projection = null;
			if(projectionL != null) {
				if(projectionL.size() != 0) {
					String s = "";
					for(int i = 0; i < projectionL.size(); i++) {
						s += projectionL.get(i).item_name.toString() + ", ";
					}
					s = s.substring(0, s.length() - 2);
					pNode = new ProjectionNode(s);
					projection =new DefaultMutableTreeNode(pNode);
					result = projection;
				}
				
			}
			//create boolean expression node (selection node)
			BooleanExpr bE = o.getSelectPredicate();
			DefaultMutableTreeNode select = null;
			if(bE != null) {
				System.out.println("hehe" + bE.toString());
				SelectionNode sNode = new SelectionNode(bE.toString());	
				select = new DefaultMutableTreeNode(sNode);
				if(projection != null) {					
					projection.add(select);
					
				} else {					
					result = select;
				}
			}
			DefaultMutableTreeNode join = new DefaultMutableTreeNode(t);
			if(select != null) {
				select.add(join);
			} else if (projection != null) {
				projection.add(join);
			} else {
				result = join;
			}
			
			TreeNode left = o.getLeftJoinTree();
			DefaultMutableTreeNode lTree=createNodes(left);
			join.add(lTree);
			TreeNode right = o.getRightJoinTree();
			DefaultMutableTreeNode rTree=createNodes(right);
			join.add(rTree);
			return result;
		}		
		else if(t instanceof TableNode)
		{
			TableNode o=(TableNode)t;
//			create projection node
			ProjectionNode pNode = null;
			ArrayList<Field> projectionL = o.getAttrsProjection();
			DefaultMutableTreeNode projection = null;
			if(projectionL != null) {
				if(projectionL.size() != 0) {
					String s = "";
					for(int i = 0; i < projectionL.size(); i++) {
						s += projectionL.get(i).item_name.toString() + ", ";
					}
					s = s.substring(0, s.length() - 2);
					pNode = new ProjectionNode(s);
					projection =new DefaultMutableTreeNode(pNode);
					result = projection;
				}
				
			}
			//create boolean expression node (selection node)
			BooleanExpr bE = o.getSelectPredicate();
			DefaultMutableTreeNode select = null;
			if(bE != null) {
				System.out.println("hehe" + bE.toString());
				SelectionNode sNode = new SelectionNode(bE.toString());	
				select = new DefaultMutableTreeNode(sNode);
				if(projection != null) {					
					projection.add(select);					
				} else {					
					result = select;
				}
			} 
			DefaultMutableTreeNode table = new DefaultMutableTreeNode(t);
			if(select != null) {
				select.add(table);
			} else if (projection != null) {
				projection.add(table);
			} else {
				result = table;
			}	
			return result;
		}
		return result;
	}
	/**
	 * This method initializes jTreeQuery	
	 * 	
	 * @return javax.swing.JTree	
	 */
	private JTree getJTreeQuery() {
		if (jTreeQuery == null) {
			jTreeQuery = new JTree();
			jTreeQuery.setVisible(false);
		}
		return jTreeQuery;
	}

	/**
	 * This method initializes jSPTreeView	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJSPTreeView() {
		if (jSPTreeView == null) {
			jSPTreeView = new JScrollPane();
			jSPTreeView.setBounds(new Rectangle(16, 120, 332, 140));
			jSPTreeView.setViewportView(getJTreeQuery());
		}
		return jSPTreeView;
	}

	/**
	 * This method initializes jTableQueryResult	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private JTable getJTableQueryResult() {
		if (jTableQueryResult == null) {
			jTableQueryResult=new JTable();
			jTableQueryResult.setPreferredScrollableViewportSize(new Dimension(500,700));

		}
		return jTableQueryResult;
	}

	

	/**
	 * This method initializes jSPTAQuery	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJSPTAQuery() {
		if (jSPTAQuery == null) {
			jSPTAQuery = new JScrollPane();
			jSPTAQuery.setBounds(new Rectangle(13, 31, 518, 58));
			jSPTAQuery.setViewportView(getJTAQuery());
		}
		return jSPTAQuery;
	}

	/**
	 * This method initializes jTAError	
	 * 	
	 * @return javax.swing.JTextArea	
	 */
	private JTextArea getJTAError() {
		if (jTAError == null) {
			jTAError = new JTextArea();
		}
		return jTAError;
	}

	/**
	 * This method initializes jSPError	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJSPError() {
		if (jSPError == null) {
			jSPError = new JScrollPane();
			jSPError.setBounds(new Rectangle(392, 136, 345, 57));
			jSPError.setViewportView(getJTAError());
		}
		return jSPError;
	}

	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {				
				QueryInterface thisClass = new QueryInterface();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);

			}
		});
	}

	/**
	 * This is the default constructor
	 */
	public QueryInterface() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(800, 574);
		this.setContentPane(getJContentPane());
		this.setTitle("Query");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			
			jLabel1 = new JLabel();
			jLabel1.setBounds(new Rectangle(393, 120, 74, 16));
			jLabel1.setToolTipText("Show errors of the query");
			jLabel1.setFont(new Font("Dialog", Font.BOLD, 12));
			jLabel1.setText("Errors");
			jLabel = new JLabel();
			jLabel.setBounds(new Rectangle(14, 9, 96, 16));
			jLabel.setText("Enter query");
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(jLabel, null);
			jContentPane.add(getJBtnMakeTree(), null);
			jContentPane.add(getJSPTreeView(), null);
			
			jContentPane.add(getJSPTAQuery(), null);
			
			jContentPane.add(getJSPError(), null);
			jContentPane.add(jLabel1, null);	
			
		}
		return jContentPane;
	}

}  //  @jve:decl-index=0:visual-constraint="10,-13"


class MyTreeCellRenderer extends DefaultTreeCellRenderer 
{ 
	private String dir="src/queryTree/images/";
	private Icon joinIcon = new ImageIcon(dir +"join.gif");
	private Icon projectIcon=new ImageIcon(dir + "project.gif");
	private Icon repositoryIcon=new ImageIcon(dir + "repository.gif");
	private Icon selectionIcon=new ImageIcon(dir + "selection.gif");
	
   public Component getTreeCellRendererComponent(JTree tree, 
      Object value, boolean selected, boolean expanded, 
      boolean leaf, int row, boolean hasFocus) 
   { 
      super.getTreeCellRendererComponent(tree, value, 
         selected, expanded, leaf, row, hasFocus); 
      DefaultMutableTreeNode node 
         = (DefaultMutableTreeNode)value; 
      
      
      if(node.getUserObject().getClass().toString().equals("class queryTree.TableNode"))      
      {    	  
    	  this.setIcon(repositoryIcon);
      }
      else if(node.getUserObject().getClass().toString().equals("class queryTree.JoinNode"))
      {
    	  this.setIcon(joinIcon);
      }
      
      else if(node.getUserObject().getClass().toString().equals("class queryTree.graphic.ProjectionNode"))
      {
    	  this.setIcon(projectIcon);
    	  
      }  else if(node.getUserObject().getClass().toString().equals("class queryTree.graphic.SelectionNode"))
      {
    	  this.setIcon(selectionIcon);
    	  
      } 
    	  
      return this;
   }
}